package com.jvtd.nettyim.im.client;

import com.jvtd.nettyim.im.client.handler.LoginResponseHandler;
import com.jvtd.nettyim.im.client.handler.MessageResponseHandler;
import com.jvtd.nettyim.im.codec.PacketDecoder;
import com.jvtd.nettyim.im.codec.PacketEncoder;
import com.jvtd.nettyim.im.codec.Spliter;
import com.jvtd.nettyim.im.protocol.request.LoginRequestPacket;
import com.jvtd.nettyim.im.protocol.request.MessageRequestPacket;
import com.jvtd.nettyim.im.util.SessionUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * @author Created by neal.zhang
 * @date 2020/5/26 - 20:59
 */
public class NettyClient {
    private static final int MAX_RETRY = 5;
    public static final String host = "127.0.0.1";
    public static final int port = 8000;

    public static void main(String[] args) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new Spliter());
                        ch.pipeline().addLast(new PacketDecoder());
                        ch.pipeline().addLast(new LoginResponseHandler());
                        ch.pipeline().addLast(new MessageResponseHandler());
                        ch.pipeline().addLast(new PacketEncoder());
                    }
                });
        connect(bootstrap, host, port, MAX_RETRY);
    }

    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.err.println("客户端连接服务成功.");
                Channel channel = ((ChannelFuture) future).channel();
                startConsoleThread(channel);
            } else if (retry == 0) {
                System.err.println("timeout.");
            } else {
                int order = MAX_RETRY - retry + 1;
                int delay = 1 << order;
                System.err.println(new Date() + ": 连接失败，第" + order + "次重连……" + delay);
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1),
                        delay, TimeUnit.SECONDS);
            }
        });
    }

    private static void startConsoleThread(Channel channel) {
        Scanner sc = new Scanner(System.in);
        LoginRequestPacket loginRequest = new LoginRequestPacket();
        new Thread(()->{
            //保证线程未被中断,即中断状态是未中断
            while (!Thread.interrupted()){
                if (!SessionUtil.hasLogin(channel)) {
                    System.err.print("用户名：");
                    String userName = sc.nextLine();
                    loginRequest.setUserName(userName);
                    loginRequest.setPassword("pwd");
                    channel.writeAndFlush(loginRequest);
                    waitForLoginResponse();

                }else {
                    String toUserId = sc.next();
                    String message = sc.next();
                    channel.writeAndFlush(new MessageRequestPacket(toUserId, message));
                }
            }
        }).start();
    }

    private static void waitForLoginResponse() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
